var express = require('express');
var router = express.Router();

// 导入moment
const moment = require('moment')
const AccountModel = require('../../models/AccountModel');



// 声明中间件监测登录
const checkLoginMiddleware = require('../../middlewares/checkLoginMiddleware')

// // 测试
// console.log(moment('2025-02-26').toDate());
// console.log(moment(new Date()).format('YYYY-MM-DD'));


router.get('/', (req, res) => {
  res.redirect('/account')
})


// 记账本的列表
router.get('/account', checkLoginMiddleware, function(req, res, next) {
  
  // 获取所有账单数据
  AccountModel.find().sort({time: -1}).then(data => {
    // console.log(data);
    res.render('list', {accounts: data, moment: moment})
  }).catch(err => {
    res.status(500).send('读取数据失败')
  })
  
});

// 添加记录
router.get('/account/create', checkLoginMiddleware, function(req, res, next) {
  res.render('create')
})

// 新增记录
router.post('/account', (req, res) => {
  // console.log(req.body);
  AccountModel.create({
    ...req.body,
    time: moment(req.body.time).toDate()
  }).then(res => {
    console.log(res);
  }).catch(err => {
    res.status(500).send('插入数据失败')
  })
  
  res.render('success', {msg: '添加成功了', url: '/account'})
})
 
// 删除记录
router.get('/account/:id', (req, res) => {
  const id = req.params.id
  AccountModel.deleteOne({_id: id}).then(res => {
    console.log(res);
  }).catch(err => {
    res.status(500).send('删除失败')
  })
  res.render('success', {msg: '删除成功了', url: '/account'})
})

module.exports = router;
